package com.shou.infrastructure.persistent.repository.user;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shou.domain.common.PageQueryEntity;
import com.shou.domain.user.model.entity.UserEntity;
import com.shou.domain.user.repository.IUserRepository;
import com.shou.infrastructure.persistent.dao.IUserDao;
import com.shou.infrastructure.persistent.po.UserPO;
import com.shou.infrastructure.persistent.repository.user.mapstruct.UserPOConvert;
import com.shou.types.common.Constants;
import com.shou.types.utils.RSAUtil;
import jakarta.annotation.Resource;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Repository;


import java.sql.SQLException;
import java.util.Optional;

@Repository("userRepository")
public class UserRepository implements IUserRepository {
    @Resource
    private IUserDao userDao;
    @Resource
    private UserPOConvert userPOConvert;
    @Override
    public void insert(UserEntity user) {
        UserPO userPO = userPOConvert.convertUserEntityToPO(user);
        try {
            userDao.insertSelective(userPO);
        } catch (DataIntegrityViolationException e) {
            Throwable rootCause = e.getRootCause();
            if (rootCause instanceof SQLException && "22001".equals(((SQLException) rootCause).getSQLState())) {
                throw new IllegalArgumentException("输入数据过长导致SQL执行失败: " + rootCause.getMessage());
            } else {
                throw new IllegalArgumentException(e.getMessage());
            }
        }
    }

    @Override
    public void updateUserById(UserEntity user) {
        UserPO userPO = userPOConvert.convertUserEntityToPO(user);
        userDao.updateByPrimaryKeySelective(userPO);
    }

    @Override
    public UserEntity getUserById(Integer id) {
        UserPO userPO = userDao.selectById(id);
        return userPOConvert.convertUserPOToEntity(userPO);
    }

    @Override
    public IPage<UserEntity> getUsersPage(PageQueryEntity pageQueryEntity) {
        // 根据页码和页面大小,构建分页对象 TODO 搜索条件新增，修改时间和创建时间字段
        Page<UserPO> page = new Page<>(pageQueryEntity.getPageIndex(), pageQueryEntity.getPageSize());
        // 采用模糊查询
        IPage<UserPO> pageMessage = userDao.selectPageMessageByCondition(
                page,
                pageQueryEntity.getUserId(),
                pageQueryEntity.getName(),
                pageQueryEntity.getPassword(),
                pageQueryEntity.getEmail(),
                pageQueryEntity.getPhone(),
                pageQueryEntity.getRole(),
                pageQueryEntity.getSortName(),
                pageQueryEntity.getSort()
        );
        return userPOConvert.convertUserPOPageToEntity(pageMessage);
    }

    @Override
    public UserEntity getUserByName(String userName) {
        QueryWrapper<UserPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", userName);
        UserPO userPO = userDao.selectOne(queryWrapper);
        return Optional.ofNullable(userPO)
                .map(userPOConvert::convertUserPOToEntity)
                .orElse(null);
    }

    @Override
    public void resetPassWordById(Integer id) {
        UpdateWrapper<UserPO> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id).set("password", RSAUtil.encryptByPublicKey(Constants.DEFAULT_PASSWORD));
        userDao.update(null, updateWrapper);
    }
}
